//
//  SignUtils.m
//  JiaoX
//
//  Created by northwan on 14/11/12.
//  Copyright (c) 2014年  All rights reserved.
//  参数签名

#import "SignUtils.h"

@implementation SignUtils

+(NSDictionary *)getParams:(NSDictionary *) params shouldLogin:(BOOL) hasT{
    NSMutableDictionary *mParams = [[NSMutableDictionary alloc]initWithDictionary:params];
    [mParams setObject:[[self getSig:params shouldLogin:hasT] lowercaseString] forKey:@"sig"];
    if (hasT) {
        NSString *token = [DefaultsHelper stringForKey:kAppToken];
        [mParams setObject:token forKey:@"token"];
    }
    //排序
    return mParams;
}

+(NSString *)getSig:(NSDictionary *) params shouldLogin:(BOOL) hasT{
    NSMutableDictionary *mParams = [[NSMutableDictionary alloc]initWithDictionary:params];
    if (hasT) {
        NSString *token = [DefaultsHelper stringForKey:kAppToken];
        if(token){
            [mParams setObject:token forKey:@"token"];
        }
    }

    NSArray *sortedKeys = [mParams allKeys];
    NSArray *resultArray = [sortedKeys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    
    NSString *str = [self nameValuePairsToStr:mParams keys:resultArray];
    if ([str length] > 5000) {
        str = [str substringToIndex:5000];
    }
    if(hasT){
        return [[[str stringByAppendingString:kBaseSecret] stringByAppendingString:[DefaultsHelper stringForKey:kServerSecret]] md5DecodingString];
    }
    return [[str stringByAppendingString:kBaseSecret] md5DecodingString];
}


/**
 * 对请求参数编辑
 * @param 参数
 */
+(NSString *)nameValuePairsToStr:(NSDictionary *)params keys:(NSArray *)shortKeys{
    NSString *result = @"";
    for (NSString *key in shortKeys) {
        result = [result stringByAppendingFormat:@"%@=%@",key,params[key]];
    }
    return result;
}

@end
